<?php

class AlipayAction extends BaseAction
{

    public $token;

    public $wecha_id;

    public $alipayConfig;

    public function _initialize()
    {
        error_log("==================================come into AlipayAtion _initialize==================================", 0);
        import("@.ORG.Alipay.alipay_notify");
        import("@.ORG.Alipay.alipay_submit");
        error_log("AlipayAction out_trade_no******************************" . $_GET['order_sn'], 0);
        // $_GET['out_trade_no']
        if ($_GET['out_trade_no']) {
            $order_info = M("Consultation")->where(array(
                "order_sn" => $_GET['out_trade_no']
            ))->find();
            $this->token = $order_info['token'];
            error_log("AlipayAction GET out_trade_no token=============================" . $this->token, 0);
        } else {
            $this->token = $_GET['token'];
            error_log("AlipayAction GET token=============================" . $this->token, 0);
        }
        
        $this->alipayConfig = M('alipay_m_config')->where(array(
            'token' => $this->token
        ))->find();
        error_log("AlipayAction partner******************************" . $this->alipayConfig['pid'], 0);
        error_log("AlipayAction key******************************" . $this->alipayConfig['key'], 0);
        
        $alipayConfig['seller_email'] = $this->alipayConfig['name'];
        $alipayConfig['partner'] = $this->alipayConfig['pid'];
        $alipayConfig['key'] = $this->alipayConfig['key'];
        $alipayConfig['private_key_path'] = getcwd() . '/app/Lib/ORG/Alipay/rsa_private_key.pem';
        $alipayConfig['ali_public_key_path'] = getcwd() . '/app/Lib/ORG/Alipay/alipay_public_key.pem';
        $alipayConfig['sign_type'] = $this->alipayConfig['sign_type'];
        $alipayConfig['input_charset'] = 'utf-8';
        $alipayConfig['cacert'] = getcwd() . '/app/Lib/ORG/Alipay/cacert.pem';
        $alipayConfig['transport'] = $this->alipayConfig['transport'];
        
        $this->alipayConfig = $alipayConfig;
        error_log("AlipayAction partner==============================" . $this->alipayConfig['partner'], 0);
        error_log("AlipayAction key==============================" . $this->alipayConfig['key'], 0);
    }

    public function pay()
    {
        // 参数数据
        $order_sn = $_GET['order_sn'];
        error_log("alipay==============================" . $order_sn, 0);
        $order_info = M('Consultation');
        $odinfo = $order_info->where(array(
            'order_sn' => $order_sn
        ))->find();
        error_log("order_info==========================" . $odinfo['order_sn'], 0);
        $subject = '专家咨询';
        $price = $odinfo['consult_fee'];
        error_log("price===============================" . $price, 0);
        //
        $alipayConfig = $this->alipayConfig;
        error_log("seller_email******************************" . $this->alipayConfig['seller_email'], 0);
        
        //
        if (! $price)
            exit('必须有价格才能支付');
            
            // 返回格式
        $format = "xml";
        // 必填，不需要修改
        
        // 返回格式
        $v = "2.0";
        // 必填，不需要修改
        
        // 请求号
        $req_id = date('Ymdhis');
        // 必填，须保证每次请求都是唯一
        
        // 支付类型
        $payment_type = "1";
        // 必填，不能修改
        // 服务器异步通知页面路径
        $notify_url = C('site_url') . '/api/malipay/notify_url.php';
        // 需http://格式的完整路径，不能加?id=123这类自定义参数
        // 页面跳转同步通知页面路径
        $call_back_url = C('site_url') . '/api/malipay/call_back_url.php';
        // 需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
        // 操作中断返回地址
        $merchant_url = C('site_url') . '/api/malipay/merchant_url.php';
        // 用户付款中途退出返回商户的地址。需http://格式的完整路径，不允许加?id=123这类自定义参数
        // 卖家支付宝帐户
        // $seller_email =trim('zfb@wawame.cn');
        $seller_email = $alipayConfig['seller_email'];
        // 商户订单号
        $out_trade_no = $order_sn;
        // 商户网站订单系统中唯一订单号，必填
        
        // 必填
        // 付款金额
        $total_fee = floatval($price);
        
        // 请求业务参数详细
        $req_data = '<direct_trade_create_req><notify_url>' . $notify_url . '</notify_url><call_back_url>' . $call_back_url . '</call_back_url><seller_account_name>' . $seller_email . '</seller_account_name><out_trade_no>' . $out_trade_no . '</out_trade_no><subject>' . $subject . '</subject><total_fee>' . $total_fee . '</total_fee></direct_trade_create_req>';
        // 必填
        error_log("req_data===============================" . $req_data, 0);
        
        // 构造要请求的参数数组，无需改动
        $para_token = array(
            "service" => "alipay.wap.trade.create.direct",
            "partner" => $alipayConfig['partner'],
            "sec_id" => $alipayConfig['sign_type'],
            "format" => $format,
            "v" => $v,
            "req_id" => $req_id,
            "req_data" => $req_data,
            "_input_charset" => "utf-8"
        );
        // 建立请求
        $alipaySubmit = new AlipaySubmit($alipayConfig);
        $html_text = $alipaySubmit->buildRequestHttp($para_token);
        
        // URLDECODE返回的信息
        $html_text = urldecode($html_text);
        
        // 解析远程模拟提交后返回的信息
        $para_html_text = $alipaySubmit->parseResponse($html_text);
        
        // 获取request_token
        $request_token = $para_html_text['request_token'];
        
        /**
         * ************************根据授权码token调用交易接口alipay.wap.auth.authAndExecute*************************
         */
        
        // 业务详细
        $req_data = '<auth_and_execute_req><request_token>' . $request_token . '</request_token></auth_and_execute_req>';
        // 必填
        
        // 构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => "alipay.wap.auth.authAndExecute",
            "partner" => $alipayConfig['partner'],
            "sec_id" => $alipayConfig['sign_type'],
            "format" => $format,
            "v" => $v,
            "req_id" => $req_id,
            "req_data" => $req_data,
            "_input_charset" => $alipayConfig['input_charset']
        );
        
        // 建立请求
        $alipaySubmit = new AlipaySubmit($alipayConfig);
        $html_text = $alipaySubmit->buildRequestForm($parameter, 'get', '支付宝');
        
        echo $html_text;
    }
    
    // 同步数据处理
    public function call_back_url()
    {
        error_log("==================================come into AlipayAtion call_back_url==================================", 0);
        $alipayNotify = new AlipayNotify($this->alipayConfig);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            
            $out_trade_no = $this->_get('out_trade_no');
            // 交易状态
            $trade_status = $this->_get('result');
            if ($trade_status == "success") {
                $order_info = M('Consultation');
                $order = $order_info->where(array(
                    'order_sn' => $out_trade_no
                ))->find();
                if ($order) {
                    $user = M('Userinfo')->where(array(
                        "id" => $order['userinfo_id']
                    ))->find();
                    if ($order['status'] >= 2) {
                        $this->success("该订单已经支付,请勿重复操作", U('Userinfo/consultationInfo', array(
                            'token' => $order['token'],
                            'id' => $order['id']
                        )));
                    }
                    
                    $money_paid = $order['consult_fee'];
                    $order_info->where(array(
                        'order_sn' => $out_trade_no
                    ))->save(array(
                        'status' => 2,
                        'money_paid' => $money_paid,
                        'pay_time' => time()
                    ));
                    if ($order['consult_type'] == 2) {
                        error_log("******************%%%%%%%%%%%%%%%%%%%%%%%%%*********************consult_type = 2", 0);
                        $experts = M('Experts')->order('expert_id desc')->limit('3')->select();
                        foreach ($experts as $e) {
                            $row['expert_id'] = $e['expert_id'];
                            $row['order_sn'] = $out_trade_no;
                          //  $row['pay_status'] = "1";
                            $row['pay_time'] = time();
                            $row['pay_type'] = 2; // 2 支付宝支付；1微信支付
                            $row['money_paid'] = 0;
                            $data['consult_id'] = $order['id'];
                            $data['status'] = 0;
                            $data['expert_id'] = $e['expert_id'];
                            if (M('Experts_solution')->add($data)) {
                                $order_info->where(array(
                                    'order_sn' => $out_trade_no
                                ))->save(array(
                                    'status' => 3
                                )); // 咨询状态改为已分发
                            }
                            
                            M('Consult_payment')->add($row);
                        }
                    } elseif ($order['consult_type'] == 1) {
                        // 指定专家
                    } else {
                        // 无偿
                    }
                    
                    /*
                     * $pay_record_model = M('pay_record');
                     * $pay_record = $pay_record_model->where(array('ordersn'=>$out_trade_no))->find();
                     * $row['ordersn']= $out_trade_no;
                     * $row['transactionid']= $transactionid;
                     * $row['totalfee']= $money_paid;
                     * $row['tradestate']= $trade_status;
                     * $row['paymethod']="wxpay";
                     * $time=strtotime(time());
                     * $row['createtime'] = $time;
                     * if($pay_record)
                     * {
                     * $pay_record_model->where(array('ordersn'=>$out_trade_no))->save($row);
                     * }
                     * else
                     * {
                     * $pay_record_model->add($row);
                     * }
                     */
                    
                    //
                    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
                    error_log("************Alipay agent = " . $agent, 0);
                    // 分别进行判断
                    if (strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
                        $device_type = 'ios';
                    } elseif (strpos($agent, 'android')) {
                        $device_type = 'android';
                    } else {
                        $device_type = 'other';
                    }
                    error_log("************Alipay device_type = " . $device_type, 0);
                    $this->success("交易成功", U('Expert/alipay_success', array(
                        'device_type' => $device_type,
                        'token' => $order['token'],
                        'wecha_id' => $user['wecha_id']
                    )));
                } else {
                    exit('订单不存在');
                }
            } else {
                exit('付款失败');
            }
        } else {
            exit('交易验证失败');
        }
    }

    public function notify_url()
    {
        error_log("==================================come into AlipayAtion notify_url==================================", 0);
        $alipayNotify = new AlipayNotify($this->alipayConfig);
        $doc = new DOMDocument();
        $doc->loadXML($alipayNotify->decrypt($_POST['notify_data']));
        $out_trade_no = $doc->getElementsByTagName("out_trade_no")->item(0)->nodeValue;
        $order_info = M("Consultation")->where(array(
            "order_sn" => $out_trade_no
        ))->find();
        $token = $order_info['token'];
        $alipay_m_config = M('alipay_m_config')->where(array(
            'token' => $token
        ))->find();
        $alipayConfig['partner'] = $alipay_m_config['pid'];
        $alipayConfig['key'] = $alipay_m_config['key'];
        $alipayConfig['private_key_path'] = $this->alipayConfig['private_key_path'];
        $alipayConfig['ali_public_key_path'] = $this->alipayConfig['ali_public_key_path'];
        $alipayConfig['sign_type'] = $alipay_m_config['sign_type'];
        $alipayConfig['input_charset'] = 'utf-8';
        $alipayConfig['cacert'] = $this->alipayConfig['cacert'];
        $alipayConfig['transport'] = $alipay_m_config['transport'];
        $alipayNotify = new AlipayNotify($alipayConfig);
        $verify_result = $alipayNotify->verifyNotify();
        error_log("==================================come into AlipayAtion notify_url() verify_result=" . $verify_result, 0);
        if ($verify_result) 
        { // 验证成功
          
            // 解析notify_data
          // 注意：该功能PHP5环境及以上支持，需开通curl、SSL等PHP配置环境。建议本地调试时使用PHP开发软件
            if (! empty($doc->getElementsByTagName("notify")->item(0)->nodeValue)) 
            {
                // 商户订单号
                $out_trade_no = $doc->getElementsByTagName("out_trade_no")->item(0)->nodeValue;
                // 支付宝交易号
                $trade_no = $doc->getElementsByTagName("trade_no")->item(0)->nodeValue;
                // 交易状态
                $trade_status = $doc->getElementsByTagName("trade_status")->item(0)->nodeValue;
                
                $total_fee = $doc->getElementsByTagName("total_fee")->item(0)->nodeValue;
                
                $create_time = $doc->getElementsByTagName("gmt_create")->item(0)->nodeValue;
                
                if ($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') 
                {
                    $pay_record_model = M('pay_record');
                    $pay_record = $pay_record_model->where(array(
                        'order_sn' => $out_trade_no
                    ))->find();
                    $data['order_sn'] = $out_trade_no;
                    $data['transaction_id'] = $trade_no;
                    $data['total_fee'] = $total_fee;
                    $data['trade_state'] = $trade_status;
                    $data['pay_method'] = "alipay";
                    $time = strtotime($create_time);
                    $data['create_time'] = $time;
                    /**
                     * if($pay_record){
                     * error_log("==================================come into AlipayAtion notify_url pay_record save********************",0);
                     * $pay_record_model->where(array('order_sn'=>$out_trade_no))->save($data);
                     * }else{
                     * error_log("==================================come into AlipayAtion notify_url pay_record add********************",0);
                     * $pay_record_model->add($data);
                     * }*
                     */
                    error_log("==================================come into AlipayAtion notify_url   order_info********************", 0);
                    
                    $order_info = M('Consultation');
                    $odinfo = $order_info->where(array(
                        'order_sn' => $out_trade_no
                    ))->find();
                    if ($odinfo) 
                    {
                        error_log("******************|||||||||||||||||||||||||||||*********************status=" . $odinfo['status'], 0);
                        if ($odinfo['status'] >= 2) 
                        {
                            error_log("******************|||||||||||||||||||||||||||||*********************status>=2", 0);
                            // $this->success("该订单已经支付,请勿重复操作",U('Product/orderDetail',array('token'=>$odinfo['token'],'order_sn'=>$odinfo['order_sn'])));
                            $this->success("该订单已经支付,请勿重复操作", U('Userinfo/consultationInfo', array(
                                'token' => $odinfo['token'],
                                'id' => $odinfo['id']
                            )));
                        } 
                        else 
                        {
                            $money_paid = $odinfo['consult_fee'];
                            $order_info->where(array('order_sn' => $out_trade_no
                            ))->save(array(
                                'status' => 2,
                                'money_paid' => $money_paid,
                                'pay_time' => time()
                            ));
                            if ($odinfo['consult_type'] == 2) {
                                error_log("******************|||||||||||||||||||||||||||||*********************consult_type = 2", 0);
                                $experts = M('Experts')->order('expert_id desc')->limit('3')->select();
                                foreach ($experts as $e) 
                                {
                                    error_log("******************|||||||||||||||||||||||||||||*********************foreach expert_id =" . $e['expert_id'], 0);
                                    $row['expert_id'] = $e['expert_id'];
                                    $row['order_sn'] = $out_trade_no;
                                    $row['pay_status'] = "1";
                                    $row['pay_time'] = time();
                                    $row['pay_type'] = 2; // 2 支付宝支付；1微信支付
                                    $row['money_paid'] = 0;
                                    $data['consult_id'] = $odinfo['id'];
                                    $data['status'] = 0;
                                    $data['expert_id'] = $e['expert_id'];
                                    if (M('Experts_solution')->add($data)) {
                                        $order_info->where(array(
                                            'order_sn' => $out_trade_no
                                        ))->save(array(
                                            'status' => 3
                                        )); // 咨询状态改为已分发
                                    }
                                    error_log("******************|||||||||||||||||||||||||||||*********************Experts_solution=" . M('Experts_solution')->getLastSql(), 0);
                                    M('Consult_payment')->add($row);
                                    error_log("******************|||||||||||||||||||||||||||||*********************Consult_payment=" . M('Consult_payment')->getLastSql(), 0);
                                }
                            } 
                            elseif ($odinfo['consult_type'] == 1) 
                            {
                                // 指定专家
                            } 
                            else 
                            {
                                // 无偿
                            }
                        }
                    }
                    echo "success"; // 请不要修改或删除
                }
                echo "success"; // 请不要修改或删除
            }
            echo "success"; // 请不要修改或删除
        } 
        else 
        {
            // 验证失败
            echo "fail";
            
            // 调试用，写文本函数记录程序运行情况是否正常
            // logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        }
    }
}
?>